package com.stox.client.ui.javafx.chartingy.model.node;

import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.paint.Color;
import javafx.scene.shape.Polygon;

import com.stox.client.ui.javafx.chartingy.model.Rectangle;
import com.stox.client.ui.javafx.chartingy.model.axis.DateAxis;
import com.stox.client.ui.javafx.chartingy.model.plot.Data;
import com.stox.client.ui.javafx.core.util.CSS;
import com.stox.client.ui.javafx.core.util.UI;
import com.stox.shared.core.model.Bar;
import com.stox.shared.core.model.Scrip;

public class AreaDataNode extends AbstractPriceNode {

	private final Polygon polygon = new Polygon();

	public AreaDataNode(final Data<Scrip, Bar> data) {
		super(data);
		getChildren().add(polygon);
		UI.style(this, CSS.barNode);
		UI.style(polygon, CSS.areaDataNode);
		data.getPlot().colorProperty().addListener(new ChangeListener<Color>() {
			@Override
			public void changed(final ObservableValue<? extends Color> observable, final Color oldValue, final Color newValue) {
				updateColor();
			}
		});
		updateColor();
	}

	@Override
	public void updateColor() {
		final Color color = getData().getPlot().getColor();
		final String col = "rgba(" + (color.getRed() * 200) + "," + (color.getGreen() * 200) + "," + (color.getBlue() * 200) + ", 0.3);";
		polygon.setStyle("-fx-bar-color:" + col + ";");
	}

	@Override
	public void layoutChartChildren() {
		final Data<Scrip, Bar> data = getData();
		final Bar bar = data.getExtraValue();
		Bar previousBar = null;
		final int size = data.getPlot().getData().size();
		if (data.getIndex() < (size - 1)) {
			previousBar = data.getPlot().getData().get(data.getIndex() + 1).getExtraValue();
		} else {
			return;
		}

		final DateAxis dateAxis = data.primaryChart().getDateAxis();
		final double x = dateAxis.getDisplayPosition(data.getIndex());
		final double width = dateAxis.getUnitWidth();
		final double high = getDisplayPosition(bar.getHigh());
		final double low = getDisplayPosition(bar.getLow());

		final Rectangle rectangle = getRectangle();
		rectangle.setX(x - (width / 2));
		rectangle.setWidth(width);
		rectangle.setY(high);
		rectangle.setHeight(low - high);

		final double previousY = getDisplayPosition(previousBar.getClose());
		final double currentY = getDisplayPosition(bar.getClose());
		final double lowY = data.getPlot().getChart().getChartContentArea().getHeight();
		polygon.getPoints().clear();
		polygon.getPoints().addAll(rectangle.getX(), previousY, x + (width / 2), currentY, x + (width / 2), lowY, rectangle.getX(), lowY);
	}

}
